﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using br.com.SistemaChamados;
using br.com.SistemaChamados.Controller;
using br.com.SistemaChamados.Controller.Common;
using br.com.SistemaChamados.Model;
using br.com.SistemaChamados.Model.Common;
using br.com.SistemaChamados.Enum;
using br.com.SistemaChamados.Constants;
using System.Web.Security;
using br.com.SistemaChamados.Util;

public partial class Pages_CallClosureSolution : System.Web.UI.Page
{
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        ViewStateUserKey = Session.SessionID;
    }

    protected void Page_PreInit(object sender, EventArgs e)
    {
        br.com.SistemaChamados.Model.Common.User loggedUser = new br.com.SistemaChamados.Model.Common.User();
        UserController userController = new UserController();
        if (Session[UserConstants.SESSION_USER_LOGGED_IN] != null)
        {
            loggedUser.Id = Convert.ToInt32(Session[UserConstants.SESSION_USER_LOGGED_IN]);
            loggedUser = userController.GetUser(loggedUser);
            this.MasterPageFile = MasterPageDefiner.defineMasterPageByAccessRole(loggedUser.Profile);
            ((Label)Master.FindControl("lblUser")).Text = loggedUser.Name;
            this.Title = "SysCall - Sistema de chamados [logado como " + loggedUser.Name + "]";
        }
        else
        {
            Response.Redirect("~/Pages/Login/Login.aspx");
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (User.IsInRole("ADMIN") || User.IsInRole("TECHNICAL"))
        {
            if (!IsPostBack)
            {
                FillData();
            }
        }
        else
        {
            FormsAuthentication.SignOut();
            Response.Clear();
            Response.Redirect("~/Pages/Login/Login.aspx");
        }
    }

    private void FillData()
    {
        try
        {
            Call call = new Call();
            CallController callController = new CallController();
            Call newCall = new Call();
            newCall.Id = Convert.ToInt32(Session[CallConstants.SESSION_CALL_ID]);
            call = callController.GetCall(newCall);
            txbProblem.Text = Convert.ToString(call.ProblemDescription);
            User user = new User();
            UserController userController = new UserController();
            User newUser = new User();
            newUser.Id = call.UserOpen.Id;
            user = userController.GetUser(newUser);
            txbUserName.Text = Convert.ToString(user.Name);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    private void GetAnnex()
    {
        try
        {
            Call call = new Call();
            call.Id = Convert.ToInt32(Session[CallConstants.SESSION_CALL_ID]);
            Annex annex = new Annex();
            AnnexController annexController = new AnnexController();
            annex = annexController.GetAnnexByCall(call);
             if (annex != null)
             {
                 string finalAddressAnnex = Request.PhysicalApplicationPath + @"Uploads\" + annex.Description;
                 Response.ContentType = "" + finalAddressAnnex + "";
                 Response.TransmitFile(@"" + finalAddressAnnex + "");
                 Response.End();
             }
             else
             {
                 Response.Write(@"<script language='javascript'>alert('Não há anexo para o chamado.') </script>");
             }
        }
        catch (Exception ex)
        {
            
            throw ex;
        }
    }

    protected void btnAnnex_Click(object sender, EventArgs e)
    {
        GetAnnex();
    }

    protected void btnFinishCall_Click(object sender, EventArgs e)
    {
        try
        {
            Call call = new Call();
            call.Id = Convert.ToInt32(Session[CallConstants.SESSION_CALL_ID]);
            CallController callController = new CallController();
            call.SolutionDescription = Convert.ToString(txbSolution.Text);
            call.Observation = "";
            CallStatus callStatus = new CallStatus();
            callStatus.Id = 3;
            call.CallStatus = callStatus;
            User userClose = new User();
            userClose.Id = Convert.ToInt32(Session[UserConstants.SESSION_USER_LOGGED_IN]);
            call.UserFinish = userClose;
            call.DateClosing = DateTime.Now;
            EnumCRUDState resultOperation = callController.UpdateCall(call);
            if (resultOperation == EnumCRUDState.SQL_SUCCESS)
            {
                call.Id = Convert.ToInt32(Session[CallConstants.SESSION_CALL_ID]);
                Annex annex = new Annex();
                AnnexController annexController = new AnnexController();
                annex = annexController.GetAnnexByCall(call);
                AnnexRemoval(annex);
                Response.Write(@"<script language='javascript'>alert('Chamado encerrado com sucesso.');</script>");
                Response.Redirect("CallClosure.aspx");                
            }
            else
            {
                Response.Write(@"<script language='javascript'>alert('Ocorreu um erro ao encerrar o chamado. Tente novamente. <br> </script>");
            }

        }
        catch (Exception ex)
        {
            Response.Write(@"<script language='javascript'>alert('Ocorreu um erro ao encerrar o chamado: <br>" + ex.Message +
                               ".');</script>");
        }
    }

    private EnumGenericState AnnexRemoval(Annex annex)
    {
        EnumGenericState resultAnnex = EnumGenericState.GENERIC_STATE_UNKNOW;
        try
        {
            if (annex != null && System.IO.File.Exists(annex.Description))
            {
                annex.Id = Convert.ToInt32(Session[CallConstants.SESSION_CALL_ID]);
                AnnexController annexController = new AnnexController();
                EnumCRUDState resultOperation = annexController.DeleteAnnex(annex);
                if (resultOperation == EnumCRUDState.SQL_SUCCESS)
                {
                    resultAnnex = EnumGenericState.GENERIC_STATE_SUCCESS;
                    System.IO.FileInfo file = new System.IO.FileInfo(annex.Description);
                    file.Delete();                    
                }
                else
                {                    
                    resultAnnex = EnumGenericState.GENERIC_STATE_FAILED;
                }
            }
            else
            {
                resultAnnex = EnumGenericState.GENERIC_STATE_SUCCESS;                
            }
            return resultAnnex;
        }
        catch (Exception ex)
        {
            resultAnnex = EnumGenericState.GENERIC_STATE_FAILED;
            return resultAnnex;
            throw ex;
        }
    }
}